package com.travel.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;

import com.travel.core.AbstractDao.Direction;
import com.travel.core.DaoFactory;
import com.travel.dao.ITourDao;
import com.travel.entities.Spot;

public class MoreDataServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    private static final Logger LOGGER = LogManager.getLogger(MoreDataServlet.class);

    private static final ITourDao TOUR_DAO = DaoFactory.getDao(ITourDao.class);

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // response.getWriter().append("Served at: ").append(request.getContextPath());

        // String start = request.getParameter("start");
        // String limit = request.getParameter("limit");
        String dataClass = request.getParameter("dataClass");
        String currPage = request.getParameter("page");
        response.setCharacterEncoding("utf-8");

        try {
            // int index = Integer.parseInt(start);
            // int pageSize = Integer.parseInt(limit);
            int currPage1 = Integer.parseInt(currPage);
            int pageSize = 10;
            if ("01".equals(dataClass)) {
                List<Spot> resultList = TOUR_DAO.selectList("spotId", "spotAvgRating", Direction.DESC,
                        (currPage1 - 1) * pageSize, pageSize);
                long totalProperty = TOUR_DAO.selectCount();
                JSONObject jsonOb = new JSONObject();// 最外层json
                JSONArray jsonArray1 = new JSONArray();
                for (Spot u : resultList) {
                    JSONObject json = new JSONObject();
                    json.put("spotId", u.getSpotId());
                    json.put("spotName", u.getSpotName());
                    json.put("spotAvgRating", u.getSpotAvgRating());
                    json.put("spotRatingCount", u.getSpotRatingCount());
                    jsonArray1.put(json);
                }
                jsonOb.put("totalProperty", totalProperty);
                jsonOb.put("root", jsonArray1);
                response.getWriter().append(jsonOb.toString());
            } else if ("02".equals(dataClass)) {

            } else if ("03".equals(dataClass)) {

            } else {

            }
        } catch (Exception ex) {
            LOGGER.error(ex.getLocalizedMessage(), ex);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}
